/**
* @Title: institution_detail_ctrl.js
* @Description: TODO
* Copyright: Copyright (c) 2014 
 * Company:中国平安
*
* @Project HIMS-FWA
* @author EX-chenyonghong001
* @date 2014年10月17日 下午2:38:47
* @version V1.0
*/
;
(function(){
	'use strict';
	
	var app = angular.module('fwa.mainApp');
	app.controller('relationCtrl', ['$scope','$http','CommunityService','$modal','$state','$stateParams','relationService','BaseURL','Modal',
	                                function($scope,$http,CommunityService,$modal,$state,$stateParams,relationService,baseUrl,Modal){
//	     CommunityService.getBaseCode('{codeType:\'dePartment\',departmentType:\'1\'}');
//	     CommunityService.getBaseCode('{codeType:\'dePartment\',departmentType:\'1\'}');
	     CommunityService.getBaseCode('{codeType:\'provincialDep\'}');
	     $scope.communityService = CommunityService;
	     $scope.UrlParams = $stateParams;
	     $scope.UrlParams.page = 0;
	     $scope.UrlParams.pageSize = 20;
	     $scope.institutionDetail={};
	       $scope.authority={
	        		add:1,
	        		update:1,
	        		deleted:1
	        };
	     //选中tab抛出改变窗口事件
		 setTimeout(function(){
				$(window).trigger('resize');
		},100);
	     //获取联系人信息
	     $scope.onSubmit = function(){
	    
		     relationService.queryRelationData($scope.UrlParams).success(function(res){
		    	 var id = $scope.UrlParams.providerid;
		    	 $scope.responsible = res.responsible;
		    	 $scope.contacts = res.contacts;
		    	 $scope.institutionDetail = res.provider;
		    	 $scope.tableData =  res.result;
		    	 $scope.authority=res.authority;
		    	 if(!$scope.contacts){
		    		 var modalInstance= $modal.open({
		   		      templateUrl: baseUrl+'views/hcpms/institution/relation2_info_add.html',
		   		      backdrop:'static',
		   			  size:'sm',
		   			  controller: function($scope, $state,$http,$modalInstance,Modal){
		   				$scope.relationDetail1={};
		   				$scope.relationDetail2={};
		   				$scope.relationDetail1.providerid = id;
		   				$scope.relationDetail1.contactype = 1;
		   				$scope.relationDetail2.providerid = id;
		   				$scope.relationDetail2.contactype = 2;
		   				var params = [];
		   				  $scope.check = function(relationDetail,type) {
		   					  if(!relationDetail.contacts){
		   						  if(type==1){
		   							 return "医保负责人不能为空！";
		   						  }else{
		   							 return "医保联系人不能为空！";
		   						  }
		   						 
		   					  }
							  if(!relationDetail.moblie){
								  return "手机不能为空！";					  
							  }
							  if(!relationDetail.phone){
								  return "联系电话不能为空！";  
							  }
		   					  
		   				  }
		   				  $scope.add = function() {
		   					 if($scope.check($scope.relationDetail1,1)){
		   						 Modal.alert($scope.check($scope.relationDetail1,1));
		   						 return;
		   					 }
		   					 if($scope.check($scope.relationDetail2,2)){
		   						 Modal.alert($scope.check($scope.relationDetail2,2));
		   						 return;
		   					 }
		   					params.push($scope.relationDetail1);
		   					params.push($scope.relationDetail2);
		   					 $http.post(baseUrl + '/hcp/hcp/insurancePer/create.do',params).success(function(data) {
	                             if(data.state=='0')
	                             {
	                                 Modal.alert(data.msg);
                             $modalInstance.close();
	                             }else
	                             {
	                                 Modal.alert("新增失败！");
	                                 $modalInstance.close();
	                             }

	                         })
		   					
		   						
		   					}
		   				 //关闭model
		   				 $scope.onClose = function() {
		   					$modalInstance.close();
		   				 }
	  				}
		   		    });
		    		 
		    		    modalInstance.result.then(function () {
				    		$scope.onSubmit();
				    });
		    	 }
		    	
		     });
	     }

	 	$scope.showDetail = function(id) {
	 		
	 	}
	     
	     
		// 表头以及json对应的属性名称
  	var cellTemplate = 
		'<td>'+
			'<a ng-bind="data.contacts" ng-click="queryRelation(data.id)"></a>'+
		'</td>';
		$scope.columns = [  
			{
			label : '科室',
			map : 'department',
			width : '25%'
		}, {
			label : '联系人',
			map : 'contacts',
			width : '25%',
			cellTemplate:cellTemplate
		}, {
			label : '手机',
			map : 'moblie',
			width : '25%'
		}
		, {
			label : '联系电话',
			map : 'phone',
			width : '25%'
		}];
		
        $scope.queryRelationParams={};
        $scope.queryRelationParams = {
                page:"0",
                pageSize:"20"
            };
		var start = 0,
		limit = 20;
		$scope.currentTab = null;
		$scope.tabs = [ {name:'基本信息',type:'institutionInfo.institutionDetail'},
		                {name:'医保服务人员',type:'institutionInfo.doctorInfoDetail'},
			               {name:'联系信息',type:'institutionInfo.relation'}
		            ];
		
		$scope.currentTab =$scope.tabs[2];
		//切换tab页
		$scope.tabClick = function(tab) {
			$state.go(tab.type,{
				providerid:$scope.UrlParams.providerid,
				type:$scope.UrlParams.type
    		});
		}
		$scope.$on('pageTool.skipPage',function(e,v){
			
			start = limit*(v-1);
			$scope.queryRelationParams.page = start;
			$scope.onSubmit();
		});
        /**
         * 机构详细信息--查询
         * @param params
         */
        $scope.queryRelation = function (doctorId){
        	var dictionaryMap = $scope.communityService.dictionaryMap;
		    var modalInstance = $modal.open({
		      templateUrl: baseUrl+'views/hcpms/institution/relation_info_add.html',
		      backdrop:'static',
			  size:'sm',
			  controller: function($scope, $state,$http,$modalInstance,Modal){
				  $scope.dictionaryMap = dictionaryMap;
				  $scope.relationDetail = {};
				 $scope.relationDetail.id = doctorId;
			      $scope.authority={
			        		add:1,
			        		update:1,
			        		deleted:1
			        };
						$http({
							method : 'GET',
							cache : false,
							url : baseUrl + '/hcp/hcp/contact/show.do',
							params :  $scope.relationDetail
						}).success(function(response, status, headers, config) {
							$scope.relationDetail = response.result;
							 $scope.authority=res.authority;
						});
						
						$scope.add = function() {
							 $http.post(baseUrl + '/hcp/hcp/contact/update.do', $scope.relationDetail).success(function(data) {
	                             if(data.state=='0')
	                             {
	                                 Modal.alert(data.msg);
	                                 $modalInstance.close();
	                             }else
	                             {
	                                 Modal.alert("修改失败！");
	                                 $modalInstance.close();
	                             }

	                         })
						
							
						}
					
				 //关闭model
				 $scope.onClose = function() {
					$modalInstance.close();
				 }
				}
		    });
		    modalInstance.result.then(function (selectedItem) {
		    		$scope.onSubmit();
		    });
		
        }
        
        $scope.queryInsurance = function (doctorId){
        	var parms = $scope.UrlParams;
        	var dictionaryMap = $scope.communityService.dictionaryMap;
		    var modalInstance = $modal.open({
		      templateUrl: baseUrl+'views/hcpms/institution/relation2_info_add.html',
		      backdrop:'static',
			  size:'sm',
			  controller: function($scope, $state,$http,$modalInstance,Modal){
				  $scope.dictionaryMap = dictionaryMap;
				  $scope.relationDetail = {};
				 $scope.relationDetail.id = doctorId;
				 $scope.relationDetail1 ={};
				 $scope.relationDetail2 ={};
						$http({
							method : 'GET',
							cache : false,
							url : baseUrl + '/hcp/hcp/insurance/list.do',
							params : parms
						}).success(function(response, status, headers, config) {
						   	 $scope.relationDetail1 = response.responsible;
					    	 $scope.relationDetail2 = response.contacts;
						});
					var updateParam = [];
						$scope.add = function() {
							updateParam.push($scope.relationDetail1);
							updateParam.push($scope.relationDetail2);
							 $http.post(baseUrl + '/hcp/hcp/insurancePerson/update.do', updateParam).success(function(data) {
	                             if(data.state=='0')
	                             {
	                                 Modal.alert(data.msg);
	                                 $modalInstance.close();
	                             }else
	                             {
	                                 Modal.alert("修改失败！");
	                                 $modalInstance.close();
	                             }

	                         })
						
							
						}
					
				 //关闭model
				 $scope.onClose = function() {
					$modalInstance.close();
				 }
				}
		    });
		    modalInstance.result.then(function (selectedItem) {
		    		$scope.onSubmit(2);
		    });
		
        }
        
        /**
         * 机构详细信息--新增
         * @param params
         */
		//打开日期Model
		$scope.addRelation = function () {
			var id =  $stateParams.providerid;
			var dictionaryMap = $scope.communityService.dictionaryMap;
		    var modalInstance = $modal.open({
		      templateUrl: baseUrl+'views/hcpms/institution/relation_info_add.html',
		      backdrop:'static',
			  size:'sm',
			  controller: function($scope, $state,$http,$modalInstance,Modal){
				  $scope.dictionaryMap = dictionaryMap;
				  $scope.relationDetail = {};
				  $scope.relationDetail.providerid = id;
				  $scope.check = function(relationDetail) {
					  if(!relationDetail.contacts){
						  return "联系人不能为空！";					  
					  }
					  if(!relationDetail.department){
						  return "科室不能为空！";					  
					  }
					  if(!relationDetail.phone){
						  return "联系电话不能为空！";					  
					  }
   				  }
					$scope.add = function() {
						 if($scope.check($scope.relationDetail)){
							 Modal.alert($scope.check($scope.relationDetail));
							 return;
						 }
						 $http.post(baseUrl + '/hcp/hcp/contact/create.do', $scope.relationDetail).success(function(data) {
                             if(data.state=='0')
                             {
                                 Modal.alert(data.msg);
                                 $modalInstance.close();
                             }else
                             {
                                 Modal.alert("新增失败！");
                                 $modalInstance.close();
                             }

                         })
					
						
					}
				 //关闭model
				 $scope.onClose = function() {
					$modalInstance.close();
				 }
				}
		    });
		    modalInstance.result.then(function (selectedItem) {
		    		$scope.onSubmit();
		    });
		};
	    $scope.checkRows = [];
        function findCheck(d) {
            for(var i=0;i< $scope.checkRows .length;i++) {
                var checkedData =  $scope.checkRows [i];
                if(checkedData.itemId == d.itemId) {
                    return i;
                }
            }
            return -1;
        }

        $scope.$on('fwatable.checked', function(e,d){
            if(findCheck(d) == -1) {
                $scope.checkRows .push(d);
            }
        });

        $scope.$on('fwatable.unchecked', function(e,d){
            var index = findCheck(d);
            if(index != -1) {
                $scope.checkRows.splice(index,1);
            }
        });
 
        /**
         *删除联系人
         * @param params
         */
        $scope.deleteRelation = function(){
            var	checkRows =  $scope.checkRows;
            if (checkRows.length == 0) {
                Modal.alert("请勾选删除项！");
                return;
            }else
            {
                var ids = '';
                angular.forEach(checkRows,function(totalCheck,i){
                    ids+="'"+totalCheck.id+"',";
                });
                var  params= {
                ids : ids
                }
                Modal.confirm('确认删除吗？',function() {
                    $http.post(baseUrl + '/hcp/hcp/contact/delete.do', params).success(function (data) {
                        if (data.state == '0') {
                            Modal.alert(data.msg);
                        } else {
                            Modal.alert("删除失败！");
                        }
                        $scope.onSubmit(2);
                    })
                })
            }
        };
        $scope.onSubmit();
    }
	]);
})();